/***************************************************************************
 *   Copyright (C) 2007 by Ivan Vasić   								   *
 *   ivasic@gmail.com   												   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "trackerserver.h"
#include "globals.h"
#include "clientthread.h"

#include <QtCore>
#include <QtNetwork>
		
TrackerServer::TrackerServer(QObject* parent)
	:QTcpServer(parent), m_running(false)
{
	m_num_connections = 0;
	m_num_connections_denied = 0;
	m_max_connections = 0;
}

TrackerServer::~TrackerServer()
{
	qDebug() << "~TrackerServer()";
	
	if(m_running)
		stop();
}

void TrackerServer::incomingConnection( int socketDescriptor )
{
	m_max_connections = Globals::instance().settings()->value("max_connections", 0).toUInt();

	if(m_max_connections != 0 && m_num_connections >= m_max_connections)
	{
		++m_num_connections_denied;
		
		qDebug() << tr("Connection denied due to connection limit. Total connections denied so far: %1").arg(m_num_connections_denied);
		
		return;
	}
	
	ClientThread *thread = new ClientThread(socketDescriptor, this);
	connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
	connect(thread, SIGNAL(finished()), this, SLOT(connectionClosed()));
	thread->start();
	
	QMutex m;
	m.lock();
	++m_num_connections;
	emit numConnectionsChanged(m_num_connections);
	m.unlock();
}

void TrackerServer::start()
{
	quint16 port = Globals::instance().settings()->value("server_port", 23982).toUInt();
	
	qDebug() << "Starting server on port" << port;
	this->listen(QHostAddress::Any, port);
	
	if(!isListening())
	{
		qDebug() << "Error starting server on port" << port;
		qDebug() << this->errorString();
		
		m_running = false;
		
		return;
	}
	
	qDebug() << "Server successfully started.";	
	m_running = true;
	m_timeStarted = QDateTime::currentDateTime().toTime_t();
}

void TrackerServer::stop()
{
	//Sacuvaj port u settings
	Globals::instance().settings()->setValue("server_port", this->serverPort());
	
	qDebug() << "Stopping server...";
	this->close();
	if(isListening())
	{
		qDebug() << "Server could not be stopped?";
		m_running = true;
		return;
	}
	
	qDebug() << "Server stopped.";
	m_timeStarted = 0;
}

void TrackerServer::connectionClosed()
{
	QMutex m;
	m.lock();
	m_num_connections--;
	emit numConnectionsChanged(m_num_connections);
	m.unlock();
}
